import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/utils/api'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
  const loading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => {
    return !!token.value && !!user.value
  })

  // 登录
  const login = async (credentials) => {
    loading.value = true
    try {
      const response = await api.post('/api/Auth/login', credentials)
      
      // 检查响应状态
      if (response.status === 200 && response.data) {
        const { token: authToken, id, username, fullName, role, expiresAt } = response.data
        
        // 保存到状态
        token.value = authToken
        user.value = { id, username, fullName, role, expiresAt }
        
        // 保存到本地存储
        localStorage.setItem('token', authToken)
        localStorage.setItem('user', JSON.stringify(user.value))
        
        // 设置API默认请求头
        api.defaults.headers.common['Authorization'] = `Bearer ${authToken}`
        
        console.log('登录成功，保存的数据:', {
          token: authToken,
          user: user.value,
          isAuthenticated: !!authToken && !!user.value
        })
        
        return { success: true }
      } else {
        return { success: false, message: response.data?.message || '登录失败' }
      }
    } catch (error) {
      console.error('登录错误:', error)
      return { 
        success: false, 
        message: error.response?.data?.message || '登录失败，请检查网络连接' 
      }
    } finally {
      loading.value = false
    }
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    user.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    delete api.defaults.headers.common['Authorization']
  }

  // 检查token有效性
  const checkAuth = async () => {
    if (!token.value) return false
    
    try {
      // 设置请求头
      api.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
      
      // 验证token
      const response = await api.post('/api/refund/get-all', {})
      return response.status === 200
    } catch (error) {
      if (error.response?.status === 401) {
        logout()
        return false
      }
      return true // 其他错误不清除登录状态
    }
  }

  // 初始化时检查认证状态
  const initAuth = async () => {
    if (token.value) {
      const isValid = await checkAuth()
      if (!isValid) {
        logout()
      }
    }
  }

  return {
    token,
    user,
    loading,
    isAuthenticated,
    login,
    logout,
    checkAuth,
    initAuth
  }
})